package com.meta.platform.contract.service.app.impl;

import com.meta.platform.contract.domain.aggr.ContractFundRecordDo;
import com.meta.platform.contract.domain.aggr.ContractPlanFundDo;
import com.meta.platform.contract.domain.tunnel.db.ContractFundRecordRepository;
import com.meta.platform.contract.domain.tunnel.db.ContractPlanFundRepository;
import com.meta.platform.contract.intf.cmd.contractfundrecord.AddContractFundRecordCmd;
import com.meta.platform.contract.intf.entity.ContractFundRecord;
import com.meta.platform.contract.intf.ro.ContractFundRecordRo;
import com.meta.platform.contract.service.app.ContractFundRecordAppService;
import com.meta.platform.contract.service.app.ContractFundRecordQryService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 *  合同回款记录
 * @Title:      ContractFundRecordAppServiceImpl
 * @Author:     M.simple
 * @Remark:     The modified content
 * @CreateDate: 2020-12-08 15:53:39
 * @Version:    v2.0
 */
@Service
public class ContractFundRecordAppServiceImpl implements ContractFundRecordAppService {

	@Resource
	private ContractFundRecordRepository contractFundRecordRepository;

	@Resource
	private ContractPlanFundRepository planFundRepository;

	@Override
	public ContractFundRecordDo insertContractFundRecord(AddContractFundRecordCmd addContractFundRecordCmd) {

		// 查询计划
		ContractPlanFundDo planFundDo = planFundRepository.getById(addContractFundRecordCmd.getContractPlanFundId());
		if (planFundDo == null){
			throw new RuntimeException("计划不存在");
		}

		// 入库基本信息
		ContractFundRecordDo recordDo = ContractFundRecordDo.create(addContractFundRecordCmd);
		contractFundRecordRepository.insertContractFundRecord(recordDo);

		// 更新计划信息
		ContractFundRecordRo listRecordRo = new ContractFundRecordRo();
		listRecordRo.setContractPlanFundId(recordDo.getContractPlanFundId());
		List<ContractFundRecordDo> recordDos = contractFundRecordRepository.listContractFundRecordDo(listRecordRo);
		planFundDo.updateStatusAndActualAmount(recordDos);
		planFundRepository.updateContractPlanFundByPk(planFundDo);

		return recordDo;
	}
}
